package com.cjf.weather.weatherdata.service.impl;

import com.cjf.weather.weatherdata.service.WeatherDataService;
import com.cjf.weather.weatherdata.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author cjf
 * @description
 * @create 2019-03-26 16:53
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    private static final long TIME_OUT = 1800L;

    private static Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        return doGetWeather(url);
    }

    @Override
    public WeatherResponse getDataByCityName(String name) {
        String url = WEATHER_URL + "city=" + name;
        return doGetWeather(url);
    }

    private WeatherResponse doGetWeather(String url) {
        String key = url; // redis的key,redis以key存储
        String content = null; // json内容
        WeatherResponse weatherResponse = null;
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        if (stringRedisTemplate.hasKey(url)) {
            logger.info("从缓存中取数据");
            content = valueOperations.get(url);
        } else {
            // 使用httpclient进行请求
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if (responseEntity.getStatusCodeValue() == 200) {
                content = responseEntity.getBody();
                // 将数据写入到缓存，并设置多少秒失效
                valueOperations.set(url, content, TIME_OUT, TimeUnit.SECONDS);
            }
            logger.info("直接从api获取数据");
        }
        ObjectMapper objectMapper = new ObjectMapper(); // 用以解析json
        try {
            // 解析json
            weatherResponse = objectMapper.readValue(content, WeatherResponse.class);
        } catch (IOException e) {
            logger.error("出现错误:", e);
        }
        return weatherResponse;
    }

}
